<template>
  <div class="paper-list">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1>试卷管理</h1>
          <p>管理已生成的试卷，支持预览、编辑和分发</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showCreateDialog = true">
            <el-icon><Plus /></el-icon>
            创建试卷
          </el-button>
          <el-button @click="handleBatchExport">
            <el-icon><Download /></el-icon>
            批量导出
          </el-button>
        </div>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-card>
        <el-form :model="filterForm" :inline="true">
          <el-form-item label="试卷标题">
            <el-input
              v-model="filterForm.search"
              placeholder="请输入试卷标题"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="试卷类型">
            <el-select v-model="filterForm.paper_type" placeholder="请选择" clearable>
              <el-option label="正式考试" value="formal" />
              <el-option label="模拟考试" value="mock" />
              <el-option label="练习试卷" value="practice" />
              <el-option label="竞赛试卷" value="competition" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="filterForm.status" placeholder="请选择" clearable>
              <el-option label="草稿" value="draft" />
              <el-option label="待审核" value="pending" />
              <el-option label="已发布" value="published" />
              <el-option label="已归档" value="archived" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="filterForm.date_range"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6" v-for="stat in paperStats" :key="stat.key">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" :style="{ backgroundColor: stat.color }">
                <el-icon><component :is="stat.icon" /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stat.value }}</div>
                <div class="stat-label">{{ stat.label }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 试卷列表 -->
    <div class="paper-table">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>试卷列表</span>
            <div class="header-controls">
              <el-tooltip content="刷新列表" placement="top">
                <el-button :icon="Refresh" @click="loadPapers" />
              </el-tooltip>
            </div>
          </div>
        </template>

        <el-table
          :data="filteredPapers"
          @selection-change="handleSelectionChange"
          @row-click="viewPaper"
          v-loading="loading"
        >
          <el-table-column type="selection" width="55" />

          <el-table-column prop="title" label="试卷标题" min-width="200">
            <template #default="{ row }">
              <div class="paper-title">
                <el-link type="primary" @click.stop="viewPaper(row)">
                  {{ row.title }}
                </el-link>
                <div class="paper-meta">
                  <el-tag :type="getTypeColor(row.paper_type)" size="small">
                    {{ getTypeLabel(row.paper_type) }}
                  </el-tag>
                  <el-tag :type="getStatusColor(row.status)" size="small">
                    {{ getStatusLabel(row.status) }}
                  </el-tag>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="试卷信息" width="250">
            <template #default="{ row }">
              <div class="paper-info">
                <div>总分：{{ row.total_score }}分</div>
                <div>时长：{{ row.duration }}分钟</div>
                <div>题目：{{ row.total_questions }}题</div>
                <div>及格分：{{ row.passing_score }}分</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="template_name" label="来源模板" width="180">
            <template #default="{ row }">
              <el-link
                v-if="row.template_name"
                type="info"
                @click.stop="viewTemplate(row.template_id)"
              >
                {{ row.template_name }}
              </el-link>
              <span v-else class="text-placeholder">无模板</span>
            </template>
          </el-table-column>

          <el-table-column label="难度分析" width="180">
            <template #default="{ row }">
              <div class="difficulty-analysis">
                <div class="difficulty-level">
                  <el-rate
                    :model-value="getDifficultyLevel(row)"
                    disabled
                    size="small"
                  />
                </div>
                <div class="difficulty-stats">
                  <span v-if="row.difficulty_stats">
                    简单 {{ row.difficulty_stats.easy || 0 }} |
                    中等 {{ row.difficulty_stats.medium || 0 }} |
                    困难 {{ row.difficulty_stats.hard || 0 }}
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="考试统计" width="150">
            <template #default="{ row }">
              <div class="exam-stats">
                <div>已考试：{{ row.exam_count || 0 }}次</div>
                <div>平均分：{{ row.avg_score || 0 }}分</div>
                <div>及格率：{{ row.pass_rate || 0 }}%</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="creator_name" label="创建人" width="100" />

          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.created_at) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click.stop="previewPaper(row)">
                预览
              </el-button>
              <el-button size="small" @click.stop="editPaper(row)">
                编辑
              </el-button>
              <el-dropdown @command="(cmd) => handleCommand(cmd, row)" @click.stop>
                <el-button size="small">
                  更多<el-icon><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="copy">复制试卷</el-dropdown-item>
                    <el-dropdown-item command="export">导出试卷</el-dropdown-item>
                    <el-dropdown-item command="distribute">分发试卷</el-dropdown-item>
                    <el-dropdown-item command="statistics" divided>统计分析</el-dropdown-item>
                    <el-dropdown-item command="archive" v-if="row.status !== 'archived'">
                      归档试卷
                    </el-dropdown-item>
                    <el-dropdown-item command="restore" v-if="row.status === 'archived'">
                      恢复试卷
                    </el-dropdown-item>
                    <el-dropdown-item command="delete" divided>删除试卷</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current_page"
            v-model:page-size="pagination.page_size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 创建试卷对话框 -->
    <CreatePaperDialog
      v-model="showCreateDialog"
      @success="handleCreateSuccess"
    />

    <!-- 分发试卷对话框 -->
    <DistributePaperDialog
      v-model="showDistributeDialog"
      :paper="selectedPaper"
      @success="handleDistributeSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, Download, Refresh, ArrowDown,
  Document, TrendCharts, User, DataBoard
} from '@element-plus/icons-vue'
import { examPaperApi } from '@/api/examPaper'
import CreatePaperDialog from './components/CreatePaperDialog.vue'
import DistributePaperDialog from './components/DistributePaperDialog.vue'
import { format } from 'date-fns'

const router = useRouter()

// 响应式数据
const showCreateDialog = ref(false)
const showDistributeDialog = ref(false)
const selectedPaper = ref(null)
const papers = ref([])
const selectedPapers = ref([])
const loading = ref(false)

// 筛选表单
const filterForm = reactive({
  search: '',
  paper_type: '',
  status: '',
  date_range: []
})

// 分页
const pagination = reactive({
  current_page: 1,
  page_size: 20,
  total: 0
})

// 统计数据
const paperStats = computed(() => [
  {
    key: 'total',
    label: '总试卷数',
    value: pagination.total,
    color: '#409EFF',
    icon: 'Document'
  },
  {
    key: 'published',
    label: '已发布',
    value: papers.value.filter(p => p.status === 'published').length,
    color: '#67C23A',
    icon: 'TrendCharts'
  },
  {
    key: 'exams',
    label: '考试次数',
    value: papers.value.reduce((sum, p) => sum + (p.exam_count || 0), 0),
    color: '#E6A23C',
    icon: 'DataBoard'
  },
  {
    key: 'avg_score',
    label: '平均分数',
    value: papers.value.length > 0
      ? Math.round(
          papers.value.reduce((sum, p) => sum + (p.avg_score || 0), 0) / papers.value.length
        )
      : 0,
    color: '#F56C6C',
    icon: 'User'
  }
])

// 计算属性
const filteredPapers = computed(() => {
  let result = papers.value

  if (filterForm.search) {
    result = result.filter(paper =>
      paper.title.toLowerCase().includes(filterForm.search.toLowerCase())
    )
  }

  if (filterForm.paper_type) {
    result = result.filter(paper => paper.paper_type === filterForm.paper_type)
  }

  if (filterForm.status) {
    result = result.filter(paper => paper.status === filterForm.status)
  }

  if (filterForm.date_range && filterForm.date_range.length === 2) {
    const [startDate, endDate] = filterForm.date_range
    result = result.filter(paper => {
      const paperDate = paper.created_at.split(' ')[0]
      return paperDate >= startDate && paperDate <= endDate
    })
  }

  return result
})

// 方法
const loadPapers = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current_page,
      page_size: pagination.page_size,
      ordering: '-created_at'
    }
    const response = await examPaperApi.getPapers(params)
    papers.value = response.data.results
    pagination.total = response.data.count
  } catch (error) {
    console.error('Failed to load papers:', error)
    ElMessage.error('加载试卷列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current_page = 1
  loadPapers()
}

const handleReset = () => {
  Object.assign(filterForm, {
    search: '',
    paper_type: '',
    status: '',
    date_range: []
  })
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.page_size = size
  loadPapers()
}

const handleCurrentChange = (page: number) => {
  pagination.current_page = page
  loadPapers()
}

const handleSelectionChange = (selection: any[]) => {
  selectedPapers.value = selection
}

const viewPaper = (paper: any) => {
  router.push(`/exam-paper/papers/${paper.id}`)
}

const previewPaper = (paper: any) => {
  router.push(`/exam-paper/papers/${paper.id}/preview`)
}

const editPaper = (paper: any) => {
  router.push(`/exam-paper/papers/${paper.id}/edit`)
}

const viewTemplate = (templateId: string) => {
  router.push(`/exam-paper/templates/${templateId}`)
}

const handleBatchExport = async () => {
  if (selectedPapers.value.length === 0) {
    ElMessage.warning('请选择要导出的试卷')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要导出选中的 ${selectedPapers.value.length} 份试卷吗？`,
      '确认导出',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    const paperIds = selectedPapers.value.map(p => p.id)
    const response = await examPaperApi.batchExportPapers(paperIds)

    // 下载ZIP文件
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `试卷导出_${format(new Date(), 'yyyyMMdd_HHmmss')}.zip`
    link.click()
    window.URL.revokeObjectURL(url)

    ElMessage.success('试卷导出成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to export papers:', error)
      ElMessage.error('试卷导出失败')
    }
  }
}

const handleCommand = async (command: string, paper: any) => {
  switch (command) {
    case 'copy':
      await copyPaper(paper)
      break
    case 'export':
      await exportPaper(paper)
      break
    case 'distribute':
      distributePaper(paper)
      break
    case 'statistics':
      viewStatistics(paper)
      break
    case 'archive':
      await archivePaper(paper)
      break
    case 'restore':
      await restorePaper(paper)
      break
    case 'delete':
      await deletePaper(paper)
      break
  }
}

const copyPaper = async (paper: any) => {
  try {
    const response = await examPaperApi.copyPaper(paper.id)
    ElMessage.success('试卷复制成功')
    loadPapers()
  } catch (error) {
    console.error('Failed to copy paper:', error)
    ElMessage.error('试卷复制失败')
  }
}

const exportPaper = async (paper: any) => {
  try {
    const response = await examPaperApi.exportPaper(paper.id)
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${paper.title}.json`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('试卷导出成功')
  } catch (error) {
    console.error('Failed to export paper:', error)
    ElMessage.error('试卷导出失败')
  }
}

const distributePaper = (paper: any) => {
  selectedPaper.value = paper
  showDistributeDialog.value = true
}

const viewStatistics = (paper: any) => {
  router.push(`/exam-paper/papers/${paper.id}/statistics`)
}

const archivePaper = async (paper: any) => {
  try {
    await examPaperApi.updatePaper(paper.id, { status: 'archived' })
    ElMessage.success('试卷归档成功')
    loadPapers()
  } catch (error) {
    console.error('Failed to archive paper:', error)
    ElMessage.error('试卷归档失败')
  }
}

const restorePaper = async (paper: any) => {
  try {
    await examPaperApi.updatePaper(paper.id, { status: 'published' })
    ElMessage.success('试卷恢复成功')
    loadPapers()
  } catch (error) {
    console.error('Failed to restore paper:', error)
    ElMessage.error('试卷恢复失败')
  }
}

const deletePaper = async (paper: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除试卷"${paper.title}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await examPaperApi.deletePaper(paper.id)
    ElMessage.success('试卷删除成功')
    loadPapers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete paper:', error)
      ElMessage.error('试卷删除失败')
    }
  }
}

const handleCreateSuccess = () => {
  showCreateDialog.value = false
  loadPapers()
}

const handleDistributeSuccess = () => {
  showDistributeDialog.value = false
  selectedPaper.value = null
  ElMessage.success('试卷分发成功')
}

// 辅助方法
const getTypeColor = (type: string) => {
  const colors = {
    formal: 'primary',
    mock: 'success',
    practice: 'warning',
    competition: 'danger'
  }
  return colors[type] || 'info'
}

const getTypeLabel = (type: string) => {
  const labels = {
    formal: '正式考试',
    mock: '模拟考试',
    practice: '练习试卷',
    competition: '竞赛试卷'
  }
  return labels[type] || type
}

const getStatusColor = (status: string) => {
  const colors = {
    draft: 'info',
    pending: 'warning',
    published: 'success',
    archived: 'info'
  }
  return colors[status] || 'info'
}

const getStatusLabel = (status: string) => {
  const labels = {
    draft: '草稿',
    pending: '待审核',
    published: '已发布',
    archived: '已归档'
  }
  return labels[status] || status
}

const getDifficultyLevel = (paper: any) => {
  const stats = paper.difficulty_stats || {}
  const total = (stats.easy || 0) + (stats.medium || 0) + (stats.hard || 0)
  if (total === 0) return 1

  const weightedSum = (stats.easy || 0) * 1 + (stats.medium || 0) * 2 + (stats.hard || 0) * 3
  return Math.round(weightedSum / total)
}

const formatDate = (dateString: string) => {
  return format(new Date(dateString), 'yyyy-MM-dd HH:mm')
}

// 生命周期
onMounted(() => {
  loadPapers()
})
</script>

<style scoped>
.paper-list {
  padding: 24px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 64px);
}

.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  color: var(--el-text-color-primary);
}

.title-section p {
  margin: 0;
  color: var(--el-text-color-regular);
  font-size: 14px;
}

.filter-section {
  margin-bottom: 24px;
}

.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  height: 100%;
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: white;
  font-size: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  line-height: 1.2;
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.paper-table {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.paper-title {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.paper-meta {
  display: flex;
  gap: 8px;
}

.paper-info {
  font-size: 13px;
  line-height: 1.5;
}

.difficulty-analysis {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.difficulty-level {
  margin-bottom: 4px;
}

.difficulty-stats {
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.exam-stats {
  font-size: 13px;
  line-height: 1.5;
}

.text-placeholder {
  color: var(--el-text-color-placeholder);
  font-style: italic;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .paper-list {
    padding: 16px;
  }

  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .header-actions {
    width: 100%;
    display: flex;
    gap: 12px;
  }

  .stats-section .el-col {
    margin-bottom: 16px;
  }

  .el-table {
    font-size: 12px;
  }
}
</style>